package elephant.rpc.network.netty;

import java.net.InetSocketAddress;

import elephant.rpc.server.core.NetworkService;
import elephant.rpc.server.message.RPCMessage;
import elephant.rpc.server.session.RPCSession;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 
 * @author skydu
 *
 */
@Sharable
public class NettyServerHandler extends SimpleChannelInboundHandler<RPCMessage> {
    //
    private NetworkService networkService;
    //
    public NettyServerHandler(NetworkService networkService){
    	this.networkService=networkService;
    }
    //
    @Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
    	RPCSession session=new RPCSession();
    	session.channel=new NettyChannel(ctx.channel());
    	InetSocketAddress address=((InetSocketAddress)ctx.channel().remoteAddress());
    	session.remoteHost = address.getHostString();
    	session.remotePort = address.getPort();
		ctx.channel().attr(RPCSession.SESSION_KEY).set(session);
		networkService.onSessionCreate(session);
	}
    //
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    	RPCSession session=ctx.channel().attr(RPCSession.SESSION_KEY).get();
    	networkService.onSessionDisconnected(session);
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, RPCMessage msg) throws Exception {
		RPCSession session=ctx.channel().attr(RPCSession.SESSION_KEY).get();
		networkService.onMessageReceived(session,msg);
	}
}

